package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.jnlp.FileContents;
import javax.servlet.http.HttpServletRequest;

/**
 * 自定义zuul过滤器,只需要添加@component注解
 * zuul自动配置过滤器
 */
@Component
public class AccessFilter extends ZuulFilter {
    //前置?后置?路由?错误处理?
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }
    //过滤器顺序号
    @Override
    public int filterOrder() {
        return 6;
    }
    //针对当前这次请求,是否执行过滤代码
    @Override
    public boolean shouldFilter() {
        /*
         * 如果请求的商品执行过滤,如果是用户或者订单,则跳过不执行
         */
        //获取请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取调用的服务id
        String str = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);

        return "item-service".equalsIgnoreCase(str);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //获取瑞快死对象

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //接收token参数
        String token = request.getParameter("token");
        //如果没有token
        if(StringUtils.isBlank(token)){
            System.out.println("1111111111111");
            //阻止继续访问
            ctx.setSendZuulResponse(false);
            //返回相应
            ctx.addZuulResponseHeader("content-type","application/json");
            ctx.setResponseStatusCode(JsonResult.NOT_LOGIN);
            ctx.setResponseBody(JsonResult
                    .err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("not login")
                    .toString());
        }
        return null;//这个返回值在当前版本中不发回任何作用,返回任何数据都无效
    }
}
